package de.bluetooth.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.UUID;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.util.Log;

public class BluetoothServer extends Thread
{	
	ArrayList<BluetoothClient> clients;
	
	BluetoothServerSocket serverSocket;
	
	String serviceName;
	Handler messageHandler;
	boolean active;
	
	UUID uid;
	
	public BluetoothServer(Handler messageHandler, String serviceName)
	{
		super();
		this.messageHandler=messageHandler;
		this.serviceName=serviceName;
		
		active=true;
		
		uid = UUID.fromString("f5efb9d2-deaf-4af8-a304-8739fe2109ab");
		clients = new ArrayList<BluetoothClient>();
	}
	
	public void run() 
	{
		try 
		 {
			 BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
			 serverSocket = bluetoothAdapter.listenUsingRfcommWithServiceRecord(serviceName,uid);
			 
			 while(active)
			 {
				 Log.i("BluetoothServer", "Waiting for Connection");
				 BluetoothSocket socket = serverSocket.accept();
				 
				 BluetoothClient client = new BluetoothClient(messageHandler,socket);
				 clients.add(client);
				 client.start();
				 
				 Log.i("BluetoothServer", "Client connection established: "+client.device.getName());
			 }

	     } catch (IOException e) { 
	    	 this.handleError(e);
	     }
	}
	
	public void stopit()
	{
		this.active=false;
		
		for(BluetoothClient client:clients)
			client.active=false;
		
	}
	

	public void broadcast(String message)
	{
		for(BluetoothClient client:clients)
		{
			client.sendMessage(message);
		}
	}
	
	public void handleError(Exception exception)
	{
		System.out.println("Exception occured on server: "+exception.getMessage());
		Log.i("Exception occured on server", exception.getMessage());
	}
	
}
